<?
include("session.php"); 
include("database.php");

$action = $_GET['action'];
$admin_agent_ids = array("hncsgj01");

 if($action == "get") {
	$sql = "select * from hngj_task where id=".$_GET['id']; 
	$arr = $db->getOneRecordArray($sql);
	echo array_to_json($arr);

} else if($action == "del") {
	$sql = "delete from hngj_task where id=".$_GET['id']; 
	$db->query($sql);
	$sql = "delete from hngj_callinfo where task_id=".$_GET['id']; 
	$db->query($sql);
	$sql = "delete from hngj_import where task_id=".$_GET['id']; 
	$db->query($sql);
	echo "ok";

} else if($action == "list") {
	$condition = "1=1";
	if(isset($_GET['biz_type'])) {
		$condition .= " and biz_type=".$_GET['biz_type'];
	}
	$sql = "select id,task_name,biz_type,callout_number,call_count,free_count,success_count, '' as success_rate, fail_count, appt_count, other_count, task_status, last_call_time, create_time, text_file from hngj_task where $condition order by last_call_time desc, id desc"; 
	// echo $sql;
	echo to_grid_json($db, $sql, $dic_data, array("task_name"=>"blue_color_mapper","success_count"=>"red_color_mapper", "task_status"=>"task_status_mapper", "text_file"=>"text_file_mapper", "last_call_time"=>"yellow_color_mapper", 'success_rate'=>"success_rate_mapper"));

} else if($action == "list_back") {
	$condition = "task_id=".$_GET['task_id']." and call_result=0 and agent_id<>''";
	$sql = "select agent_id, count(id) as cnt, '' as op_link, task_id from hngj_callinfo where $condition group by agent_id"; 
	// echo $sql;
	echo to_grid_json($db, $sql, $dic_data, array("agent_id"=>"blue_color_mapper","cnt"=>"backable_count_mapper","op_link"=>"op_link_mapper_1"), false);

} else if($action == "list_batch") {
	$sql = "select id, import_time, import_count, '' as op_link from hngj_import where task_id=".$_GET['task_id']." order by id desc"; 
	//echo $sql;
	echo to_grid_json($db, $sql, $dic_data, array("import_time"=>"blue_color_mapper","import_count"=>"red_color_mapper","op_link"=>"op_link_mapper_2"));

} else if($action == "add") { 
	unset($_POST['id']);
	$_POST['create_time'] = date("Y-m-d H:i:s");
	$db->doInsert('hngj_task', $_POST);
	echo 'ok';

}  else if($action == "edit") {
	$id = $_POST['id'];
	unset($_POST['id']);
	$db->doUpdate('hngj_task', $_POST, "id=$id");
	echo 'ok';

}  else if($action == "import_data") {
	$f = fopen($_FILES['upload_file']['tmp_name'], "r");
	$i = 0;
	$prefix_sql = "insert into hngj_callinfo_temp(telephone, cust_name, cust_addr, task_id) values ";
	$values_arr = array();
	while(($line=fgets($f)) != "") {
		$arr = explode(",", str_replace("'","‘",$line));
		if( empty($arr[1]) ) {
			$arr[1] = "未知";
		}
		if( empty($arr[2]) ) {
			$arr[2] = "未知";
		}
		/*
		$rec = array(
			'telephone'=>str_replace("\n","", str_replace("\r","",$arr[0])),
			'cust_name'=>str_replace("\n","", str_replace("\r","",$arr[1])),
			'cust_addr'=>str_replace("\n","", str_replace("\r","",$arr[2])),
			'task_id'=>$_GET['task_id']
		);
		//$db->setOnlyPrintSql(true);
		//$db->doInsert("hngj_callinfo_temp", $rec);
		*/
		$values_arr[] = "('".filter_special_chars($arr[0])."','".filter_special_chars($arr[1])."','".filter_special_chars($arr[2])."',".$_GET['task_id'].")";
		$i++;
		if($i % 1000 == 0) {  // 改成每1000条写一次数据，提升处理效率; 2014/9/17
			$db->query($prefix_sql . implode(",", $values_arr));  
			$values_arr = array();
		}
	}
	if(count($values_arr) > 0) {
		$db->query($prefix_sql . implode(",", $values_arr)); // 将非1000整数的剩余记录写入temp表
	}
	$db->query("insert into hngj_import(task_id, import_time) values(".$_GET['task_id'].", '".date("Y-m-d H:i:s")."')");
	$import_id = mysql_insert_id();

	// 用中间一次性自动去重，提升效率;
	$sql = "insert into hngj_callinfo(telephone, cust_name, cust_addr, task_id, import_id) 
	select telephone, cust_name, cust_addr, task_id, $import_id from hngj_callinfo_temp where task_id=". $_GET['task_id'] ." group by telephone";
	//" and telephone not in(select telephone from hngj_callinfo where task_id=".$_GET['task_id'].")";
	$db->query($sql);
	$import_count = mysql_affected_rows(); // 取到去重后导入的条数

	$db->query("update hngj_import set import_count=$import_count where id=$import_id"); // 更新导入批次的统计数
	$db->query("update hngj_task set task_status=1, call_count=call_count+{$import_count}, free_count=free_count+{$import_count} where id=".$_GET['task_id']);
	$db->query("delete from hngj_callinfo_temp where task_id=".$_GET['task_id']); // 清除中间表的数据
	echo "<script> parent.upload_completed($import_count);</script>"; // 提示记录导入条数


}  else if($action == "import_text") {
	$text_file_name = date("YmdHis").".html";
	$f = move_uploaded_file($_FILES['upload_file']['tmp_name'], "./text/".$text_file_name);
	$db->query("update hngj_task set text_file='$text_file_name' where id=".$_GET['task_id']); // 更新模板文件名
	echo "<script> parent.upload_completed();</script>"; // 提示导入成功


}  else if($action == "clear_data") {
	$db->query("update hngj_task set task_status=0, call_count=0, success_count=0, fail_count=0,free_count=0 where id=".$_GET['task_id']);
	$db->query("delete from hngj_callinfo where task_id=".$_GET['task_id']); // 清除外呼表的数据
	echo "ok";


} else if($action == "clear_free_data") {
	$db->query("update hngj_task set task_status=0, call_count=call_count-free_count,free_count=0 where id=".$_GET['task_id']);
	$db->query("delete from hngj_callinfo where agent_id='' and task_id=".$_GET['task_id']); // 清除外呼表的数据
	echo "ok";


} else if($action == "set_task_run_flag") {
	$task_status = 1;
	if($_GET['flag'] == "pause") {
		$task_status = 3; // 暂停状态
	} 
	$db->query("update hngj_task set task_status=$task_status where id=".$_GET['task_id']);
	echo "ok";


} else if($action == "clear_batch") {
	$rec = $db->getOneRecord("select task_id, import_count from hngj_import where id=".$_GET['import_id']);
	$db->query("delete from hngj_callinfo where import_id=".$_GET['import_id']); // 清除外呼表的数据
	$db->query("delete from hngj_import where id=".$_GET['import_id']); // 清除批次表的数据
	$db->query("update hngj_task set call_count=call_count-".$rec['import_count'].", 
	free_count=free_count-".$rec['import_count']." where id=".$rec['task_id']);
	echo "ok";


} else if($action == "dispatch") {
	$task_id = $_POST['task_id'];
	$agent_ids = explode(",", $_POST['agent_ids']);
	$agent_count = count($agent_ids);
	/*$count = $db->getOneValue("select call_count from hngj_task where id=$task_id");
	if($count == 0) {
		echo "no record";
		exit;
	}*/
	$count = $_POST['dispatch_count']; // 让前端输入要分配的条数
	$per = round($count/$agent_count);  // 每个座席要分配的条数
	if($per == 0) { // // 如果记录条数小于座席人数，则直接分配给第一个座席工号
		$per = $count;
		$agent_count = 1;
	}
	$dispatched_count = 0;

	for($k=0; $k<$agent_count; $k++) {
		//$start = $k*$per;  // 不用计算start值，直接每次从0开始即可；2014/5/23
		$ids = array();
		$db->query("select id from hngj_callinfo where task_id=$task_id and agent_id='' limit 0,$per");
		while($db->next_record()) {
			$ids[] = $db->f("id");
			$dispatched_count++;
		}
		if(count($ids) > 0) {
			$db->query("update hngj_callinfo set agent_id='".$agent_ids[$k]."' where id in (". implode(",", $ids) .")");
		}
	}
	
	$db->query("update hngj_task set task_status=2, free_count=free_count-{$dispatched_count} where id=$task_id");
	echo "ok";


} else if($action == "set_back") {
	$db->query("select id from hngj_callinfo where task_id=".$_GET['task_id']." and call_result=0 and agent_id='".$_GET['agent_id']."' limit 0,".$_GET['limit']);
	$ids = array();
	while($db->next_record()) {
		$ids[] = $db->f("id");
	}
	$db->query("update hngj_callinfo set agent_id='' where id in (". join(",", $ids).")");
	$count = @mysql_affected_rows();
	$db->query("update hngj_task set free_count=free_count+{$count} where id=".$_GET['task_id']);
	echo "ok";


} else if($action == "set_back_all") { // 一次全部回收; 2014/11/13
	$db->query("update hngj_callinfo set agent_id='' where task_id=".$_GET['task_id']." and call_result=0 and agent_id<>''");
	$count = @mysql_affected_rows();
	$db->query("update hngj_task set free_count=free_count+{$count} where id=".$_GET['task_id']);
	echo "ok";


} else if($action == "get_select_options") {
	$condition = "task_status<>3"; // 不显示暂停状态
	if(isset($_GET['list_all'])) {
		$condition = "1=1"; // 显示全部
	}
	$arr = array();
	$db->query("select id, task_name from hngj_task where $condition order by id desc");
	while($db->moveNext()) {
		$arr[] = $db->f("id") .",". $db->f("task_name");
	}
	echo join("$", $arr);
}


function task_status_mapper($v, $arr) {
	if($v == 0) {
		return "<a href=\"javascript:import_data(".$arr['id'].")\">待导入号码</a>";
	} else if($v == 3) {
		return "<font color=gray>已暂停</font>";
	}  else {
		return "<a href=\"javascript:import_data(".$arr['id'].")\">导入</a> <a href=\"javascript:dispatch_task(".$arr['id'].")\" style=\"color:#993333\">分配</a> <a href=\"javascript:set_back(".$arr['id'].")\" style=\"color:gray\">回收</a> <a href=\"javascript:show_import_batch(".$arr['id'].")\" style=\"color:#336600\">批次</a> <a href=\"javascript:show_agent_score(".$arr['id'].")\" style=\"color:red\">排名</a>";
	}
}

function text_file_mapper($v, $arr) {
	if($v == '') {
		return "<a href=\"javascript:import_text(".$arr['id'].")\">导入模板</a>";
	} else {
		return "<a href=\"javascript:show_text(\\'$v\\')\">查看模板</a>";
	} 
}

function op_link_mapper_1($v, $arr) {
	return "<a href=\"javascript:set_back(".$arr['task_id'].", \\'".$arr['agent_id']."\\')\">回收任务</a>";
}

function op_link_mapper_2($v, $arr) {
	return "<a href=\"javascript:clear_batch(".$arr['id'].")\">清除批次</a>";
}


function backable_count_mapper($v, $arr) {
		return "<input type=text id=\\'set_back_".$arr['task_id']."_".$arr['agent_id']."\\' value=$v size=5>";
}

function yellow_color_mapper($v) {
	return "<font color=#cc0000>$v</a>";
}

function success_rate_mapper($v, $arr) {
	if($arr['task_status'] == 0 || $arr['success_count']==0) {
		return "0";
	} else {
		$n = $arr['success_count'] / ($arr['success_count'] + $arr['fail_count'] + $arr['appt_count'] + $arr['other_count']);
		if($n > 0) {
			return "<font color=blue>".substr(strval($n*100),0,4) . "%</font>";
		}
	}
}

?>